package com.wangtongxiao.controller;

import com.wangtongxiao.beans.Value;
import com.wangtongxiao.dto.ResuDTO;
import com.wangtongxiao.exception.CRUDException;
import com.wangtongxiao.services.ValueServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/DictionaryValue")
public class ValueController {
    @Autowired
    ValueServices valueServices;

    @RequestMapping("/getAll.action")
    public ArrayList<Value> getAll() {
        return valueServices.getAll();
    }

    @RequestMapping("add.action")
    public ResuDTO add(@Valid Value value, BindingResult bindingResult) throws CRUDException {
        ResuDTO resuDTO = new ResuDTO();
        resuDTO.setResult(ResuDTO.SUCCESS);

        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors
            ) {
                System.out.println(fieldError.getDefaultMessage());
                throw new CRUDException(fieldError.getDefaultMessage());
            }
        }

        boolean add = valueServices.add(value);
        if (!add) {
            throw new CRUDException("添加失败");
        }

        return resuDTO;

    }
@RequestMapping("editBefore.action")
    public Value editBefore(String id){

    return valueServices.get(id);
    }
    @RequestMapping("edit.action")
    public ResuDTO edit(Value value) throws CRUDException {
        ResuDTO resuDTO = new ResuDTO();
        resuDTO.setResult(ResuDTO.SUCCESS);
        boolean edit = valueServices.edit(value);
        if (!edit){
            throw new CRUDException("修改失败");
        }
        return resuDTO;
    }



    @RequestMapping("del.action")
    public ResuDTO del(@RequestBody String[] ids) throws CRUDException {
        ResuDTO resuDTO =new ResuDTO();
        resuDTO.setResult(ResuDTO.SUCCESS);
        boolean del = valueServices.del(ids);
        if (!del){
            throw new CRUDException("删除失败");
        }
        return resuDTO;

    }


}
